# -*- coding: utf-8 -*-
"""
Created on Thu Jul 29 14:44:05 2021

@author: Administrator
"""

import logging
import os
from logging import handlers

log_path = "D:/mydata/logs/spider/"


class Logger(object):
    # 日志级别映射
    level_map = {
        'debug': logging.DEBUG,
        'info': logging.INFO,
        'warning': logging.WARNING,
        'error': logging.ERROR
    }

    def __init__(self, log_file_path=log_path + "spider.log", level="error", when='D', backCount=3,
                 fmt="%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s"):
        # 创建
        if not os.path.exists(log_path):
            os.makedirs(log_path)
            open(log_file_path, 'w')
        # logger对象
        self.logger = logging.getLogger(log_file_path)
        # 格式
        format_str = logging.Formatter(fmt)
        # 级别
        self.logger.setLevel(self.level_map.get(level))
        # 1 控制台输出
        sh = logging.StreamHandler()
        sh.setFormatter(format_str)
        # hanlder添加到logger
        self.logger.addHandler(sh)
        # 2 log文件输出
        th = handlers.TimedRotatingFileHandler(filename=log_file_path, when=when, backupCount=backCount,
                                               encoding='utf-8')
        th.setFormatter(format_str)
        self.logger.addHandler(th)

    def error(self, msg):
        self.logger.error(msg)
